package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.IUserService;
import com.mdd.admin.validate.UserCreateValidate;
import com.mdd.admin.validate.UserSearchValidate;
import com.mdd.admin.validate.UserUpdateRoleValidate;
import com.mdd.admin.validate.UserUpdateValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.LegalCooperationBindListedVo;
import com.mdd.admin.vo.UserDetailVo;
import com.mdd.admin.vo.UserListedVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.LegalCooperationBind;
import com.mdd.common.entity.user.User;
import com.mdd.common.enums.UserRoleEnum;
import com.mdd.common.mapper.LegalCooperationBindMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.UrlUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    UserMapper userMapper;

    @Resource
    LegalCooperationBindMapper legalCooperationBindMapper;

    /**
     * 用户信息列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<UserListedVo>
     */
    @Override
    public PageResult<UserListedVo> list(PageValidate pageValidate, UserSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        MPJQueryWrapper<User> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.selectAll(User.class).select("t2.area_name as areaname, t3.name as company")
                .leftJoin("legal_area_city t2 on t.area_id = t2.area_id")
                .leftJoin("legal_areas t3 on t.a_id = t3.id")
                .eq("t.is_delete", 0)
                .orderByDesc("t.id");

        if (StringUtils.isNotNull(searchValidate.getKeyword())
                && StringUtils.isNotEmpty(searchValidate.getKeyword())) {
            String keyword = searchValidate.getKeyword();
            mpjQueryWrapper.nested(wq->wq
                    .like("t.real_name", keyword).or()
                    .like("t.mobile", keyword));
        }

        IPage<UserListedVo> iPage = userMapper.selectJoinPage(
                new Page<>(page, limit),UserListedVo.class, mpjQueryWrapper);
        for (UserListedVo vo : iPage.getRecords()) {
            if (StringUtils.isEmpty(vo.getAreaname())) {
                vo.setAreaname("其他");
            }
            if (StringUtils.isEmpty(vo.getCompany())) {
                vo.setCompany("其他");
            }
            if (StringUtils.isEmpty(vo.getAiToken())) {
                vo.setAiTokenband("未绑定");
            } else {
                vo.setAiTokenband("已绑定");
            }
            MPJQueryWrapper<LegalCooperationBind> wrapper = new MPJQueryWrapper<>();
            wrapper.selectAll(LegalCooperationBind.class)
                    .select("t2.real_name as creditorUserName, t3.real_name as cooperatorUserName")
                    .leftJoin("la_user t2 on t2.id = t.creditor_user_id")
                    .leftJoin("la_user t3 on t3.id = t.cooperator_user_id")
                    .eq("t.creditor_user_id", vo.getId());
            LegalCooperationBindListedVo bind = legalCooperationBindMapper.selectJoinOne(LegalCooperationBindListedVo.class, wrapper);
            if (bind != null) {
                vo.setCooperatorUserName(bind.getCooperatorUserName());
            }
        }
        return PageResult.iPageHandle(iPage);
    }

    /**
     * 用户信息详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return User
     */
    @Override
    public UserDetailVo detail(Integer id) {
        User model = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("id", id)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        org.springframework.util.Assert.notNull(model, "数据不存在");

        UserDetailVo vo = new UserDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setAvatar(UrlUtils.toAbsoluteUrl(model.getAvatar()));
        vo.setIsLawyerName(UserRoleEnum.getMsgByCode(vo.getIsLawyer().intValue()));
        return vo;
    }

    /**
     * 用户信息新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(UserCreateValidate createValidate) {
        User model = new User();
        model.setAId(createValidate.getAId());
        model.setSn(createValidate.getSn());
        model.setAvatar(UrlUtils.toRelativeUrl(createValidate.getAvatar()));
        model.setRealName(createValidate.getRealName());
        model.setNickname(createValidate.getNickname());
        model.setUsername(createValidate.getUsername());
        model.setPassword(createValidate.getPassword());
        model.setMobile(createValidate.getMobile());
        model.setMoney(createValidate.getMoney());
        model.setSalt(createValidate.getSalt());
        model.setSex(createValidate.getSex());
        model.setChannel(createValidate.getChannel());
        model.setIsDisable(createValidate.getIsDisable());
        model.setIsNew(createValidate.getIsNew());
        model.setLastLoginIp(createValidate.getLastLoginIp());
        model.setLastLoginTime(createValidate.getLastLoginTime());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setLocalArea(createValidate.getLocalArea());
        model.setIsLawyer(createValidate.getIsLawyer());
        model.setIsAuthentication(createValidate.getIsAuthentication());
        model.setIdNumbe(createValidate.getIdNumbe());
        model.setIdentityCardNumber(createValidate.getIdentityCardNumber());
        model.setReverseIdentityCard(createValidate.getReverseIdentityCard());
        model.setSystemUser(createValidate.getSystemUser());
        model.setToken(createValidate.getToken());
        model.setAiToken(createValidate.getAiToken());
        model.setCrmebUser(createValidate.getCrmebUser());
        model.setSignFlowId(createValidate.getSignFlowId());
        model.setSignShortLink(createValidate.getSignShortLink());
        model.setSignPreviewLink(createValidate.getSignPreviewLink());
        model.setCooperationShareCode(createValidate.getCooperationShareCode());
        model.setAreaId(createValidate.getAreaId());
        userMapper.insert(model);
    }

    /**
     * 用户信息编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(UserUpdateValidate updateValidate) {
        User model = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("id",  updateValidate.getId())
                        .eq("is_delete", 0)
                        .last("limit 1"));

        org.springframework.util.Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setAId(updateValidate.getAId());
        model.setSn(updateValidate.getSn());
        model.setAvatar(UrlUtils.toRelativeUrl(updateValidate.getAvatar()));
        model.setRealName(updateValidate.getRealName());
        model.setNickname(updateValidate.getNickname());
        model.setUsername(updateValidate.getUsername());
        model.setPassword(updateValidate.getPassword());
        model.setMobile(updateValidate.getMobile());
        model.setMoney(updateValidate.getMoney());
        model.setSalt(updateValidate.getSalt());
        model.setSex(updateValidate.getSex());
        model.setChannel(updateValidate.getChannel());
        model.setIsDisable(updateValidate.getIsDisable());
        model.setIsNew(updateValidate.getIsNew());
        model.setLastLoginIp(updateValidate.getLastLoginIp());
        model.setLastLoginTime(updateValidate.getLastLoginTime());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setLocalArea(updateValidate.getLocalArea());
        model.setIsLawyer(updateValidate.getIsLawyer());
        model.setIsAuthentication(updateValidate.getIsAuthentication());
        model.setIdNumbe(updateValidate.getIdNumbe());
        model.setIdentityCardNumber(updateValidate.getIdentityCardNumber());
        model.setReverseIdentityCard(updateValidate.getReverseIdentityCard());
        model.setSystemUser(updateValidate.getSystemUser());
        model.setToken(updateValidate.getToken());
        model.setAiToken(updateValidate.getAiToken());
        model.setCrmebUser(updateValidate.getCrmebUser());
        model.setSignFlowId(updateValidate.getSignFlowId());
        model.setSignShortLink(updateValidate.getSignShortLink());
        model.setSignPreviewLink(updateValidate.getSignPreviewLink());
        model.setCooperationShareCode(updateValidate.getCooperationShareCode());
        model.setAreaId(updateValidate.getAreaId());
        userMapper.updateById(model);
    }

    @Override
    public void editRole(UserUpdateRoleValidate updateValidate) {
        User model = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("id",  updateValidate.getId())
                        .eq("is_delete", 0)
                        .last("limit 1"));

        org.springframework.util.Assert.notNull(model, "数据不存在!");
        model.setIsLawyer(updateValidate.getIsLawyer());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        userMapper.updateById(model);
    }

    /**
     * 用户信息删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        User model = userMapper.selectOne(
                new QueryWrapper<User>()
                        .eq("id", id)
                        .eq("is_delete", 0)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete("1");
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        userMapper.updateById(model);
    }

}
